package com.aggeek.springbootlearning;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * author:liuao
 * description:
 * Date: create on 21:54 2018/3/15
 * modify by: httpclient处理文件
 */
public class ProcessFileByHttpClient {

    private static int BUFFER_SIZE = 1024;

    private final static String IMG_PREFIX = "http://img.aoaoshop.com/";

    private static HttpClient httpClient = new HttpClient();

    public static File downloadPic(String romteUrl) throws IOException {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        GetMethod getMethod =new GetMethod(romteUrl);
        httpClient.executeMethod(getMethod);
        inputStream = getMethod.getResponseBodyAsStream();
        if (inputStream!=null){
            byte[] bytes = new byte[1024];
            int len;
            File file = new File("/image/temp/");
            if (!file.exists()){
                file.mkdirs();
                file.setWritable(true);
            }
            String filePath = "/image/temp/"+ UUID.randomUUID()+".jpeg";
            outputStream = new FileOutputStream(filePath);
            while((len =inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
            return new File(filePath);
        }else{
            return null;
        }

    }
    public static void main(String[] args){
        try {
            ProcessFileByHttpClient.downloadPic(IMG_PREFIX+"241997c4-9e62-4824-b7f0-7425c3c28917.jpeg");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
